package demo4.controller;


import demo4.mapper.IUserMapper;
import demo4.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Scanner;

@Component
public class UserController {
    @Autowired
    private IUserMapper userMapper;

    public void start() {
        Scanner scan = new Scanner(System.in);
        System.out.println("请选择：\n" +
                "  1.用户注册\n" +
                "  2.用户登录\n" +
                "  3.用户列表\n" +
                "  4.修改用户信息\n");
        int choice = scan.nextInt();
        switch (choice) {
            case 1:
                userReg();
                break;
            case 2:
                userLogin();
                break;
            case 3:
                userList();
                break;
            case 4:
                userUpdate();
                break;
        }
    }

    public void userReg() {
        System.out.println("开始注册");
        User user = new User();
        Scanner scan = new Scanner(System.in);
        System.out.println("请输入用户名：");
        user.setUsername(scan.nextLine());
        System.out.println("请输入密码：");
        user.setPassword(scan.nextLine());
        System.out.println("请输入昵称：");
        user.setNickname(scan.nextLine());
        System.out.println("请输入年龄：");
        user.setAge(scan.nextInt());
        if(userMapper.selectByUsername(user.getUsername())==null) {
            int result = userMapper.insert(user);
            System.out.println(result > 0 ? "注册成功" : "注册失败");
        }else{
            System.out.println("用户已存在");
        }
    }

    public void userLogin() {

        System.out.println("开始登录");
        User user ;
        Scanner scan = new Scanner(System.in);
        System.out.println("请输入用户名：");
        String username=scan.nextLine();
        System.out.println("请输入密码：");
        String password = scan.nextLine();
        user = userMapper.selectByUsername(username);
        if(user!=null){
            if(user.getPassword().equals(password)){
                System.out.println("登录成功");
            }else{
                System.out.println("登录失败，密码错误");
            }
        }else {
            System.out.println("登录失败，用户不存在");
        }
    }

    public void userList() {
        System.out.println("用户列表");
        for (User user : userMapper.selectAll()) {
            System.out.println(user);
        }
    }
    public void userUpdate() {
        System.out.println("根据用户名更改其他信息");
        User user = new User();
        Scanner scan = new Scanner(System.in);
        System.out.println("请输入用户名：");
        user.setUsername(scan.nextLine());
        System.out.println("请输入密码：");
        user.setPassword(scan.nextLine());
        System.out.println("请输入昵称：");
        user.setNickname(scan.nextLine());
        System.out.println("请输入年龄：");
        user.setAge(scan.nextInt());
        userMapper.userUpdate(user);
    }
}
